using System;
using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    class StringCompiler : IProductionCompiler {
        private readonly IProductionCompiler ProductionCompiler;

        public StringCompiler (IProductionCompiler productionCompiler) {
            ProductionCompiler = productionCompiler;
        }

        public GrammarTree Compile (ITerm term, ChoicePrecedence precedence, ProductionCompilerContext context) {
            var compositeTerm = (CompositeTerm) term;

            IProduction interpolationProduction;
            ITerm interpolationProductionTerm;

            if (compositeTerm.SubTerms.TryGetValue ("interpolation-production", out interpolationProductionTerm)) {
                interpolationProduction = ProductionCompiler.Compile (interpolationProductionTerm, null, context).Production;
            } else {
                interpolationProduction = context.Environment.Default;
            }

            return new GrammarTree (new ChoiceProduction (StringProduction.CreateTerminal (), InterpolatedStringProduction.CreateTerminal (interpolationProduction)));
        }
    }
}